/**
  ******************************************************************************
  * @file    bsp_gps.c
  * @author  Iron
  * @date    2018-07-19
  * @version v1.0
  * @brief   bsp gps c file
  */

/** @addtogroup GROUP_BSP
  */

/* includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include "FreeRTOS.h"
#include "task.h"
#include "bsp_usart_ex.h"
#include "bsp_gps.h"
#include "bsp_power.h"

/* private typedef -----------------------------------------------------------*/
/* private macro -------------------------------------------------------------*/
#define gps_delay(ms)  vTaskDelay( pdMS_TO_TICKS(ms) );

// gpio config
#define GPS_RESET_PIN    GPIO_PIN_4 // GPS_RESET: PC4 - 33
#define GPS_RESET_PORT   GPIOC
#define GPS_RESET_HIGH() HAL_GPIO_WritePin(GPS_RESET_PORT, GPS_RESET_PIN, GPIO_PIN_SET)
#define GPS_RESET_LOW()  HAL_GPIO_WritePin(GPS_RESET_PORT, GPS_RESET_PIN, GPIO_PIN_RESET)

#define GPS_PORT_RCC_INIT() __HAL_RCC_GPIOC_CLK_ENABLE();

// uart config
#define GPS_USART   BSP_UART4

/* private variables ---------------------------------------------------------*/
static bsp_usart_handle_t gps_usart;

/* private function prototypes -----------------------------------------------*/
/* private functions ---------------------------------------------------------*/

int32_t bsp_gps_gpio_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;

    GPS_PORT_RCC_INIT();

    // RESET
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Pin  = GPS_RESET_PIN;
    HAL_GPIO_Init(GPS_RESET_PORT, &GPIO_InitStruct);

    GPS_RESET_HIGH();

    return 0;
}

int32_t bps_gps_reset(void)
{
    GPS_RESET_LOW();
    gps_delay(100); // dealy 0.1s
    GPS_RESET_HIGH();
    return 0;
}

void bps_gps_power_on(void)
{
    bsp_power_set(bsp_power_gps, BSP_POWER_ON);
}

void bps_gps_power_off(void)
{
    bsp_power_set(bsp_power_gps, BSP_POWER_OFF);
}

int32_t bsp_gps_uart_init(void)
{
    return bsp_usart_ex_init(&gps_usart, GPS_USART, 9600, NULL, NULL);
}

int32_t gps_uart_send(uint8_t *data, int32_t len, uint32_t timeout)
{
    return bsp_usart_send_ex(&gps_usart, data, len, timeout);
}

int32_t gps_uart_getbyte(uint8_t *data, uint32_t timeout)
{
    return bsp_usart_getbyte_ex(&gps_usart, data, timeout);
}

int32_t gps_uart_recv(uint8_t *data, int32_t size, uint32_t timeout)
{
    return bsp_usart_recv_ex(&gps_usart, data, size, timeout);
}

int32_t bsp_gps_init(void)
{
    bsp_gps_gpio_init();
    bsp_gps_uart_init();
    return 0;
}

/**
* @}
*/

/******************* (C)COPYRIGHT 2018 ***** END OF FILE *********************/
